package br.inf.solutions.apresentacoes.ssp.control.validator;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import br.com.vexillum.control.manager.ExceptionManager;
import br.com.vexillum.control.validator.Validator;
import br.com.vexillum.util.ReflectionUtils;
import br.com.vexillum.util.Return;
import br.com.vexillum.util.SpringFactory;
import br.inf.solutions.apresentacoes.ssp.control.CityController;
import br.inf.solutions.apresentacoes.ssp.model.City;

public class CityValidator extends Validator {

	public CityValidator(Map<String, Object> mapData) {
		super(mapData);
	}

	@Override
	public Return validateSave() {
		Return ret = super.validateSave();
		if (ret.isValid())
			ret.concat(existsName());
		return ret;
	}
	
	public Return validateSearchByCriteria() {
		City cidade = (City) entity;
		Return ret = creatReturn(null, getValidationMessage(null, "searchbycriteria", false));
		try {
			for (Field field : ReflectionUtils.getSearchFields(cidade)) {
				field.setAccessible(true);
				if(!field.getName().equals("active") && field.get(cidade) != null && !field.get(cidade).toString().equals("")){
					return new Return(true);
				}
			}
		} catch (Exception e) {
			ret = new ExceptionManager(e).treatException();
		}
		return ret;
	}

	private Return existsName(){
		Return ret = new Return(true);
		City cid = (City) entity;
		HashMap<String, Object> data = new HashMap<String, Object>();
		
		data.put("sql", "FROM City WHERE name = '" + cid.getName() + "' AND state = '" + cid.getState().getId() + "'");
			
		CityController controlador = SpringFactory.getController("cityController", CityController.class, data);
		if(!controlador.searchByHQL().getList().isEmpty()){
			ret.concat(creatReturn("nome", getValidationMessage("name", "exists", true)));
		}
		return ret;
	}
}